package com.work.mp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.work.common.core.domain.AjaxResult;
import com.work.common.utils.DateUtils;
import com.work.common.utils.StringUtils;
import com.work.common.utils.http.HttpUtils;
import com.work.mp.domain.Login;
import com.work.mp.domain.weixin.AesForGetPhoneNumber;
import com.work.mp.domain.weixin.PhoneDecryptInfo;
import com.work.sys.domain.SysUser;
import com.work.sys.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginService.class);

    @Value("${mp.appId}")
    private String appId;
    @Value("${mp.secret}")
    private String secret;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private MpTokenService tokenService;


    public AjaxResult login(Login login) {
        if (StringUtils.isEmpty(login.getCode())) {
            return AjaxResult.error("微信编码不能为空");
        }
        String param = "appid=" + appId + "&secret=" + secret + "&js_code=" +
                login.getCode() + "&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String result = HttpUtils.sendGet(url,param);
        if (StringUtils.isEmpty(result)) {
            return AjaxResult.error("调用微信接口失败");
        }
        if (StringUtils.isEmpty(result)) {
            return AjaxResult.error("外部接口返回为空");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        boolean success = jsonObject.containsKey("openid") && jsonObject.containsKey("session_key");
        if (!success) {
            logger.error("请求微信登录接口失败，返回：{}", result);
            if (jsonObject.containsKey("errcode")) {
                return AjaxResult.error(jsonObject.getString("errmsg"));
            } else {
                return AjaxResult.error("请求微信登录接口失败");
            }
        }
        if (StringUtils.isEmpty(jsonObject.getString("openid"))) {
            return AjaxResult.error("未包含或者返回openid为空");
        }
        if (StringUtils.isEmpty(jsonObject.getString("session_key"))) {
            return AjaxResult.error("未包含或者返回session为空");
        }
        String openId = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        SysUser user = new SysUser();
        user.setOpenId(openId);
        List<SysUser> userList = userMapper.selectSysUserList(user);
        if (null != userList && !userList.isEmpty()) {
            user = userList.get(0);
            return encodeUser(user);
        }
        //解密手机号
        /*AesForGetPhoneNumber aes = new AesForGetPhoneNumber(
                login.getPhoneNumberEncryptedData(), login.getPhoneNumberIv(), sessionKey);
        PhoneDecryptInfo info = aes.decrypt();
        if (null == info) {
            return AjaxResult.error("解密手机号错误");
        }
        if (!info.getWatermark().getAppid().equals(appId)) {
            return AjaxResult.error("wrong appId");
        }
        user.setPhoneNumber(info.getPhoneNumber());*/
        user.setNickName(login.getWxNickname());
        user.setCreateTime(DateUtils.getNowDate());
        user.setUpdateTime(user.getCreateTime());
        user.setStatus("0");//可用
        int saveResult = userMapper.insertSysUser(user);
        if (saveResult < 0) {
            return AjaxResult.error("保存失败");
        }
        return encodeUser(user);
    }

    private AjaxResult encodeUser(SysUser user) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tk", tokenService.getToken(user));
        return AjaxResult.success(jsonObject);
    }
}
